<template>
  <div class="container">
    <!-- 面包屑 导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 列表 -->
      <el-table
        :data="rolesDataList"
        style="width: 100%"
      >
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="i1"
              :class="[i1 ===0 ? 'border_top' : '' , 'border_bottom']"
            >
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRolesRightId(scope.row,item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="i2"
                  :class="[i2 === 0 ? '' : 'border_top', 'item3_row']"
                >
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRolesRightId(scope.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                    <el-tag
                      v-for="(item3,i3) in item2.children"
                      :key="i3"
                      type="warning"
                      closable
                      @close="removeRolesRightId(scope.row,item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <!-- 索引 -->
        <el-table-column type="index"></el-table-column>

        <!-- table B-->
        <el-table-column
          label="角色名称"
          prop="roleName"
        >
        </el-table-column>
        
        <el-table-column
          label="角色描述"
          prop="roleDesc"
        >
        </el-table-column>

        <!-- 操作 -->
        <el-table-column
          label="操作"
          width="290"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
            >修改</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="showRolesDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
        <!-- table E-->

      </el-table>

    </el-card>

    <!-- 分配权限 弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="RolesDialogVisible"
      width="40%"
      @close="RolesDialogClose"
    >
      <!-- 主要内容 -->
      <el-tree
        :data="RolesDialogList"
        :props="defaultRolesDialogProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="RolesTreeRef"
      ></el-tree>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="RolesDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="rolesAuth"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      token: '',
      rolesDataList: [],
      RolesDialogVisible: false,
      RolesDialogList: [], // 树形结构数据
      defaultRolesDialogProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前等待分配角色用户的id
      roleId: '',
      // 点击分配角色权限数据
      rolesAuthData: ''
    }
  },
  created() {
    this.token = window.sessionStorage.getItem('token')
    this.getDataList()

  },
  methods: {
    // 获取角色列表
    async getDataList() {
      const { data: res } = await this.$axios.get('roles', {
        headers: {
          'Authorization': this.token
        }
      })
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
        return
      }
      this.rolesDataList = res.data
      // console.log(res)
    },
    // 删除角色指定权限
    async removeRolesRightId(role, rightId) {
      console.log(role, rightId)
      const confirm = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      console.log(confirm)

      if (confirm == 'cancel') {
        return this.$message.info('已取消删除权限')
      }


      let { data: res } = await this.$axios.delete(`roles/${role.id}/rights/${rightId}`, {
        headers: {
          'Authorization': this.token
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      console.log(res.data)
      this.$message.success('删除权限成功')
      role.children = res.data
    },
    // 获取树形所有权限列表
    async rightsList() {
      let { data: res } = await this.$axios(`rights/${'tree'}`, {
        headers: {
          'Authorization': this.token
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.RolesDialogList = res.data
      // console.log(res)
    },
    // 分配权限弹出框
    showRolesDialog(role) {
      console.log(role)
      this.roleId = role.id
      this.rightsList()
      this.getLeafKeys(role, this.defKeys)
      this.RolesDialogVisible = true
      this.rolesAuthData = role
    },
    // 通过递归的形式，获取角色下所有三级权限的id,并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      if (!node.children) {
        // console.log(node)
        return arr.push(node.id)
      }

      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 关闭 分配权限 弹窗
    RolesDialogClose() {
      this.defKeys = []
    },
    // 点击 确定 授权角色
    async rolesAuth() {
      const keys = [
        ...this.$refs.RolesTreeRef.getHalfCheckedKeys(), ...this.$refs.RolesTreeRef.getCheckedKeys()
      ]
      const rids = keys.join(',')
      const { data: res } = await this.$axios.post(`roles/${this.roleId}/rights`, { rids: rids }, {
        headers: {
          'Authorization': this.token
        }
      })
      this.RolesDialogVisible = false
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      // console.log(res)
      // this.getDataList()
      // console.log(this.roleId)
      console.log(this.rolesDataList)

      const nodes = {

      }

      console.log(this.$refs.RolesTreeRef.getHalfCheckedNodes())
      console.log(this.$refs.RolesTreeRef.getCheckedNodes())

      // this.rolesDataList.forEach(item=>{
      //   console.log(item.id)
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.item3_row {
  .el-tag {
    margin: 5px;
  }
}
</style>